// ##############################
// ####  note:  bokeweilai wifi main fun
// ####  create:  TANWENHUI (twh:谭文辉)
// ####  date:   2024/6/18
// ##############################

#include "bkwl_common.h"
#include "bkwl_network.h"
#include "bkwl_event.h"
#include "wifi_types.h"
#include "lwip/sockets.h"
#include "net.h"
bk_err_t bkwl_network_init()
{
	bk_err_t ret = BK_OK;
	tprintf("bkwl_network_init entry\n");
	tprintf("bkwl_network_init exit\n");
	return ret;
}

#if 1
void doorbell_wifi_event_cb(void *new_evt)
{
	wifi_linkstate_reason_t info = *((wifi_linkstate_reason_t *)new_evt);
	bkwl_msg_t msg;
	msg.param = info.state;

	switch (info.state)
	{
	case WIFI_LINKSTATE_STA_GOT_IP:
	{
		tprintf("WIFI_LINKSTATE_STA_GOT_IP\r\n");

		msg.event = BKWL_WIFI_STATION_CONNECTED;
		bkwl_event_send_msg(&msg);
	}
	break;

	case WIFI_LINKSTATE_STA_DISCONNECTED:
	{
		tprintf("WIFI_LINKSTATE_STA_DISCONNECTED\r\n");

		msg.event = BKWL_WIFI_STATION_DISCONNECTED;
		bkwl_event_send_msg(&msg);
	}
	break;

	case WIFI_LINKSTATE_AP_CONNECTED:
	{
		tprintf("WIFI_LINKSTATE_AP_CONNECTED\r\n");
	}
	break;

	case WIFI_LINKSTATE_AP_DISCONNECTED:
	{
		tprintf("WIFI_LINKSTATE_AP_DISCONNECTED\r\n");
	}
	break;

	default:
		tprintf("WIFI_LINKSTATE %d\r\n", info.state);
		break;
	}
}

int bkwl_network_wifi_sta_connect(char *ssid, char *key)
{
	int len;

	tprintf("bkwl_network_wifi_sta_connect ssid=%s,key=%s\n", ssid, key);

	bk_wlan_status_register_cb(doorbell_wifi_event_cb);

	wifi_sta_config_t sta_config = {0};

	len = os_strlen(key);

	if (32 < len)
	{
		tprintf("ssid name more than 32 Bytes\r\n");
		return BK_FAIL;
	}

	os_strcpy(sta_config.ssid, ssid);

	len = os_strlen(key);

	if (64 < len)
	{
		tprintf("key more than 64 Bytes\r\n");
		return BK_FAIL;
	}

	os_strcpy(sta_config.password, key);

	tprintf("ssid:%s key:%s\r\n", sta_config.ssid, sta_config.password);
	BK_LOG_ON_ERR(bk_wifi_sta_set_config(&sta_config));
	BK_LOG_ON_ERR(bk_wifi_sta_start());

	tprintf("bkwl_network_wifi_sta_connect  exit\n");
	return BK_OK;
}
#endif
